<?php

namespace App\Http\Controllers;

use App\File;
use App\Node;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Help;
use Illuminate\Support\Facades\DB;

class UpdateController extends Controller
{
    public function update()
    {
        ignore_user_abort(true); //设置关掉浏览器继续执行
        set_time_limit(0);       //设置超时
        ini_set('date.timezone', 'Asia/Shanghai');
        $dir = public_path(env('FILE_PATH'));
        $result = $this->read_all_dir($dir);
        $i = $j = 0;
        $new_file_ids = [];
        foreach ($result as $file_absolute_path) {
            $file_info = explode(DIRECTORY_SEPARATOR, $file_absolute_path);
            $filename = $file_info[count($file_info) - 1];
            $md5_file = md5_file($file_absolute_path);
            $i++;
            //            $file_new_name = $md5_file . '.' . Help::get_file_postfix($file_path);
            $new_file = $dir . '/' . $filename;
            rename($file_absolute_path, $new_file);
            $file = File::where('md5', $md5_file)->first();
            if (empty($file)) {
                $file = new File;
                $file->user_id = 1;
                $file->name = explode('.', $filename)[0];
                $file->file_name = $filename;
                $file->size = Help::formatBytes(filesize($file_absolute_path));
                $file->md5 = $md5_file;
                $file->url = '/file/' . $filename;
                $file->type = Help::get_file_type($filename);
                $file->save();
                $new_file_ids[] = $file->id;
                $j++;
            } else {
                $file->file_name != $filename && unlink($file_absolute_path);
            }
        }
        echo "扫描 $i 个文件 <br>添加了 $j 个文件";

        $old_files = File::whereNotIn('id', $new_file_ids)->get();
        foreach ($old_files as $old_file) {
            if (!is_file($dir . '/' . $old_file['file_name'])) {
                $old_file->delete();
            }
        }


    }

    protected function read_all_dir($dir)
    {
        $result = array();
        if (is_dir($dir)) {
            $handle = opendir($dir);
            if ($handle) {
                while (($file = readdir($handle)) !== false) {
                    if ($file != '.' && $file != '..') {
                        $cur_path = $dir . DIRECTORY_SEPARATOR . $file;
                        if (is_dir($cur_path)) {
                            $result = array_merge($result, $this->read_all_dir($cur_path));
                        } else {
                            $result[] = $cur_path;
                        }
                    }
                }
                closedir($handle);
            }
        }
        return $result;
    }
}
